﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using HashFoo.Rest.Common;
using HashFoo.Rest.Server;
using HashFooRest.App.ServiceDomain.RawData;
using HashFooRest.App.Web.Config;
using Ninject;
using Filter = System.Web.Mvc.Filter;

namespace HashFooRest.App.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        static StandardKernel _kernel;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new SingletonTestFilter());
            filters.Add(new ResourceSerializerFilter(DependencyResolver.Current.GetServices<IResourceSerializer>()));
            filters.Add(new QueryMetaExecutorFilter());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            RegisterResourceRoutes(routes);

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        static void RegisterResourceRoutes(RouteCollection routeCollection)
        {
            var resourceUris =
                new ResourceUriCollectionBuilder()
                    .AddFromAssemblyOf<EchoQuery>()
                    .Build();

            routeCollection.RegisterResourceRoutes(resourceUris);
        }

        protected void Application_Start()
        {
            var kernel = new Ninject.StandardKernel(
                new HandlerNinjectModule(),
                new ResourceSerializerNinjectModule());

            _kernel = kernel;
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(new HandlerControllerFactory());
        }
    }
}